import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Nabar from '../../conpoment/Nabar';
import styles from './index.module.css';

// 预约项目接口
interface AppointmentItem {
  id: string;
  title: string;
  orderTime: string;
  status: 'pending' | 'booked' | 'cancelled' | 'completed';
  type: 'check' | 'test' | 'medicine';
  appointmentDetails?: {
    date: string;
    day: string;
    time: string;
    room: string;
    available: number;
    fullDate: string;
    hospital: string;
    patient: string;
  };
}

// 患者信息接口
interface Patient {
  id: number;
  name: string;
  idNumber: string;
}

function Index() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<'pending' | 'booked'>('pending');
  const [showPatientModal, setShowPatientModal] = useState(false);
  const [selectedPatient, setSelectedPatient] = useState<Patient>({
    id: 1,
    name: '王小柯',
    idNumber: '2015****10'
  });

  // 患者列表数据
  const patients: Patient[] = [
    { id: 1, name: '王小柯', idNumber: '2015****10' },
    { id: 2, name: '李玲玲', idNumber: '2016****25' }
  ];

  // 待预约项目数据
  const pendingAppointments: AppointmentItem[] = [
    {
      id: '1',
      title: '双肾及肾血管彩色多普勒',
      orderTime: '2020-01-01 10:20:36',
      status: 'pending',
      type: 'check'
    },
    {
      id: '2',
      title: '上腹部CT平扫',
      orderTime: '2020-01-01 10:20:36',
      status: 'pending',
      type: 'check'
    }
  ];

  // 已预约项目数据 - 从本地存储读取
  const [bookedAppointments, setBookedAppointments] = useState<AppointmentItem[]>([]);

  // 从本地存储加载已预约数据
  useEffect(() => {
    const savedBooked = localStorage.getItem('bookedAppointments');
    if (savedBooked) {
      setBookedAppointments(JSON.parse(savedBooked));
    } else {
      // 如果没有保存的数据，添加一些示例数据
      const sampleData: AppointmentItem[] = [
        {
          id: '1',
          title: '双肾及肾血管彩色多普勒',
          orderTime: '2020-01-01 10:20:36',
          status: 'booked',
          type: 'check',
          appointmentDetails: {
            date: '2020-01-01',
            day: '周一',
            time: '08:30-09:30',
            room: 'CT诊室一',
            available: 1,
            fullDate: '2020-01-01 08:30-09:30',
            hospital: '四川省保健院南苑',
            patient: '王小柯'
          }
        },
        {
          id: '2',
          title: '双肾及肾血管彩色多普勒',
          orderTime: '2020-01-01 10:20:36',
          status: 'cancelled',
          type: 'check',
          appointmentDetails: {
            date: '2020-01-01',
            day: '周一',
            time: '08:30-09:30',
            room: 'CT诊室一',
            available: 1,
            fullDate: '2020-01-01 08:30-09:30',
            hospital: '四川省保健院南苑',
            patient: '王小柯'
          }
        },
        {
          id: '3',
          title: '双肾及肾血管彩色多普勒',
          orderTime: '2020-01-01 10:20:36',
          status: 'completed',
          type: 'check',
          appointmentDetails: {
            date: '2020-01-01',
            day: '周一',
            time: '08:30-09:30',
            room: 'CT诊室一',
            available: 1,
            fullDate: '2020-01-01 08:30-09:30',
            hospital: '四川省保健院南苑',
            patient: '王小柯'
          }
        }
      ];
      setBookedAppointments(sampleData);
    }
  }, []);

  const handleTabChange = (tab: 'pending' | 'booked') => {
    setActiveTab(tab);
  };

  const handlePatientSwitch = (patient: Patient) => {
    setSelectedPatient(patient);
    setShowPatientModal(false);
  };

  const handleAppointmentClick = (appointment: AppointmentItem) => {
    if (appointment.status === 'pending') {
      // 跳转到医技项目选择页面
      navigate('/medical-tech-confirm', {
        state: {
          tech: {
            id: appointment.id,
            name: appointment.title,
            department: '影像科',
            description: '医技检查项目',
            price: 200,
            duration: '30分钟',
            requirements: ['携带身份证', '预约单'],
            icon: '🔬'
          },
          time: {
            id: '1',
            date: '2024-01-15',
            time: '09:00',
            available: true
          }
        }
      });
    } else if (appointment.status === 'booked') {
      // 跳转到预约详情页面
      navigate('/medical-tech-detail', {
        state: {
          appointment: appointment
        }
      });
    }
  };

  const handleReschedule = (appointment: AppointmentItem, e: React.MouseEvent) => {
    e.stopPropagation();
    // 跳转到医技确认页面进行改签
    navigate('/medical-tech-confirm', {
      state: {
        tech: {
          id: appointment.id,
          name: appointment.title,
          department: '影像科',
          description: '医技检查项目',
          price: 200,
          duration: '30分钟',
          requirements: ['携带身份证', '预约单'],
          icon: '🔬'
        },
        time: {
          id: '1',
          date: '2024-01-15',
          time: '09:00',
          available: true
        },
        isModify: true,
        originalAppointment: appointment
      }
    });
  };

  const handleCancel = (appointment: AppointmentItem, e: React.MouseEvent) => {
    e.stopPropagation();
    if (window.confirm('确定要取消此预约吗？')) {
      // 更新预约状态为已取消
      const updatedAppointments = bookedAppointments.map(item => 
        item.id === appointment.id 
          ? { ...item, status: 'cancelled' as const }
          : item
      );
      setBookedAppointments(updatedAppointments);
      localStorage.setItem('bookedAppointments', JSON.stringify(updatedAppointments));
    }
  };

  const currentAppointments = activeTab === 'pending' ? pendingAppointments : bookedAppointments;

  return (
    <div className={styles.container}>
      {/* 顶部导航栏 */}
      <Nabar title="医技预约" sticky={false} />
      
      {/* 患者信息卡片 */}
      <div className={styles.patientCard}>
        <div className={styles.patientInfo}>
          <div className={styles.patientName}>{selectedPatient.name}</div>
          <div className={styles.patientId}>{selectedPatient.idNumber}</div>
        </div>
        <div 
          className={styles.switchButton}
          onClick={() => setShowPatientModal(true)}
        >
          <span className={styles.switchIcon}>⇄</span>
          <span className={styles.switchText}>切换</span>
        </div>
      </div>

      {/* 标签页 */}
      <div className={styles.tabs}>
        <div 
          className={`${styles.tab} ${activeTab === 'pending' ? styles.activeTab : ''}`}
          onClick={() => handleTabChange('pending')}
        >
          待预约
        </div>
        <div 
          className={`${styles.tab} ${activeTab === 'booked' ? styles.activeTab : ''}`}
          onClick={() => handleTabChange('booked')}
        >
          已预约
        </div>
      </div>

      {/* 预约项目列表 */}
      <div className={styles.appointmentList}>
        {currentAppointments.map((appointment) => (
          <div 
            key={appointment.id} 
            className={`${styles.appointmentCard} ${activeTab === 'booked' ? styles.bookedCard : ''}`}
            onClick={() => handleAppointmentClick(appointment)}
          >
            {/* 左侧蓝色条 */}
            <div className={styles.cardIndicator}></div>
            
            <div className={styles.appointmentContent}>
              <div className={styles.cardHeader}>
                <div className={styles.appointmentTitle}>{appointment.title}</div>
                {activeTab === 'booked' && (
                  <div className={`${styles.statusBadge}`} data-status={appointment.status}>
                    {appointment.status === 'booked' && <span className={styles.statusText} data-status="booked">待检查</span>}
                    {appointment.status === 'cancelled' && <span className={styles.statusText} data-status="cancelled">已取消</span>}
                    {appointment.status === 'completed' && <span className={styles.statusText} data-status="completed">已检查</span>}
                  </div>
                )}
                {activeTab === 'pending' && (
                  <div className={styles.arrowIcon}>&gt;</div>
                )}
              </div>
              {activeTab === 'booked' && appointment.appointmentDetails && (
                <div className={styles.appointmentDetails}>
                  <div className={styles.detailRow}>
                    <span className={styles.detailLabel}>预约医院</span>
                    <span className={styles.detailValue}>{appointment.appointmentDetails.hospital}</span>
                  </div>
                  <div className={styles.detailRow}>
                    <span className={styles.detailLabel}>就诊患者</span>
                    <span className={styles.detailValue}>{appointment.appointmentDetails.patient}</span>
                  </div>
                  <div className={styles.detailRow}>
                    <span className={styles.detailLabel}>检查诊室</span>
                    <span className={styles.detailValue}>{appointment.appointmentDetails.room}</span>
                  </div>
                  <div className={styles.detailRow}>
                    <span className={styles.detailLabel}>预约时间</span>
                    <span className={styles.detailValue}>{appointment.appointmentDetails.fullDate}</span>
                  </div>
                </div>
              )}
              {activeTab === 'pending' && (
                <div className={styles.appointmentTime}>
                  开单时间: {appointment.orderTime}
                </div>
              )}
            </div>
            {/* 操作按钮 - 只有待检查状态才显示 */}
            {activeTab === 'booked' && appointment.status === 'booked' && (
              <div className={styles.actionButtons} onClick={(e) => e.stopPropagation()}>
                <button 
                  className={styles.rescheduleButton}
                  onClick={(e) => handleReschedule(appointment, e)}
                >
                  改签
                </button>
                <button 
                  className={styles.cancelButton}
                  onClick={(e) => handleCancel(appointment, e)}
                >
                  取消预约
                </button>
              </div>
            )}
          </div>
        ))}
      </div>
      {/* 患者切换模态框 */}
      {showPatientModal && (
        <div className={styles.modalOverlay} onClick={() => setShowPatientModal(false)}>
          <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <span className={styles.modalTitle}>选择患者</span>
              <span className={styles.closeButton} onClick={() => setShowPatientModal(false)}>×</span>
            </div>
            <div className={styles.patientList}>
              {patients.map((patient) => (
                <div
                  key={patient.id}
                  className={`${styles.patientItem} ${
                    selectedPatient.id === patient.id ? styles.selectedPatient : ''
                  }`}
                  onClick={() => handlePatientSwitch(patient)}
                >
                  <div className={styles.patientInfo}>
                    <div className={styles.patientName}>{patient.name}</div>
                    <div className={styles.patientId}>{patient.idNumber}</div>
                  </div>
                  {selectedPatient.id === patient.id && (
                    <div className={styles.currentIndicator}>当前</div>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Index;
